﻿using System.Runtime.Serialization;
using System.Collections.Generic;
using System.Linq;
using System;

namespace YYS
{
    using System.Text;
    using System.Web.Mvc;
    using YYSService;
    using configManager = System.Configuration.ConfigurationManager;

    public class Helper
    {
        #region dbHelper
        /// <summary>
        /// 初始化dbHelper操作类
        /// </summary>
        /// <param name="Server">服务器</param>
        /// <param name="execType">操作类型</param>
        /// <param name="DataBase">数据库</param>
        /// <returns></returns>
        public static dbHelper GETdbHelper(dbHelper.EnumServer Server, dbHelper.ExecType execType, string DataBase)
        {
            return dbHelperInit(execType, DataBase, Server: Server);
        }
        /// <summary>
        /// 初始化dbHelper操作类
        /// </summary>
        /// <param name="serverIp">服务器IP</param>
        /// <param name="execType">操作类型</param>
        /// <param name="DataBase">数据库</param>
        /// <returns></returns>
        public static dbHelper GETdbHelper(string serverIp, dbHelper.ExecType execType, string DataBase, bool isSchoolServer = true)
        {
            return dbHelperInit(execType, DataBase, serverIp: serverIp, isSchoolServer: isSchoolServer);
        }

        static dbHelper dbHelperInit(dbHelper.ExecType execType, string DataBase, string serverIp = null, dbHelper.EnumServer Server = dbHelper.EnumServer._Null, bool isSchoolServer = true)
        {
            dbHelper db = Server != dbHelper.EnumServer._Null ? new dbHelper(Server) : new dbHelper(serverIp, isSchoolServer);
            db.execType = execType;
            db.DataBase = DataBase;
            db.FuncError = (ex) =>
            {
                System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(true);
                List<string> list = new List<string>();
                for (int i = 0; i < st.FrameCount; i++)
                {
                    var sf = st.GetFrame(i);
                    bool IsSystem = sf.GetMethod().DeclaringType == null || sf.GetMethod().DeclaringType.jTrim().Contains("System");
                    if (!IsSystem)
                    {
                        list.Add(string.Format("【{0}】在{1} 的 {2}；位置：{3} 行号：{4}", i, sf.GetMethod().DeclaringType, sf.GetMethod(), sf.GetFileName(), sf.GetFileLineNumber()));
                    }
                }
            };
            return db;
        }

        public static string getRemoteIp()
        {
            string ip = "";
            try
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? string.Empty;
                if (ip.Trim().Length > 0)
                {
                    if (ip.Contains(":"))
                    {
                        ip = ip.Substring(0, ip.IndexOf(':')).Trim();
                    }
                    if (ip.Contains(","))
                    {
                        ip = ip.Split(',')[0].xTrim();
                    }
                }
            }
            catch { }

            if (ip == "" || ip == "::1")
            {
                try
                {
                    if (System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                        ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                }
                catch { }
            }

            if (ip == "" || ip == "::1")
            {
                try
                {
                    System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
                    System.ServiceModel.Channels.MessageProperties properties = context.IncomingMessageProperties;
                    System.ServiceModel.Channels.RemoteEndpointMessageProperty endpoint = properties[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name] as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
                    ip = endpoint.Address;
                }
                catch { }
            }

            if (ip == "" || ip == "::1")
            {
                try
                {
                    ip = System.Web.HttpContext.Current.Request.UserHostAddress.jTrim();
                }
                catch { }
            }

            if (ip == "" || ip == "::1") return "";
            return ip;
        }

        #endregion

        public static void Log(LogModel logModel)
        {
            if (logModel == null) return;

            Action func = () =>
            {
                var sb = new StringBuilder();
                sb.AppendFormat("{0} ================", logModel.FdL_Time.ToString("yyyy-MM-dd HH:mm:ss.fff")).AppendLine();
                sb.AppendFormat("FsL_Title: {0}", logModel.FsL_Title).AppendLine();
                sb.AppendFormat("FnL_IsSystemError: {0}", logModel.FnL_IsSystemError).AppendLine();
                sb.AppendFormat("FsL_Key: {0}", logModel.FsL_Key).AppendLine();
                sb.AppendFormat("FsL_System: {0}", logModel.FsL_System).AppendLine();
                sb.AppendFormat("FsL_Page: {0}", logModel.FsL_Page).AppendLine();
                sb.AppendFormat("FsL_Method: {0}", logModel.FsL_Method).AppendLine();
                sb.AppendFormat("FxL_Detail: {0}", logModel.FxL_Detail).AppendLine();

                if (logModel.Detail.Count > 0)
                {
                    sb.Append("------------------------").AppendLine();
                    sb.AppendFormat("{0}", logModel.Detail.jConvertObjectToJson()).AppendLine();
                }
                LogCache.Instance.AddQueue(new LogData()
                {
                    logDir = YYS.API.getHostPath("~/privateFolder/{0}/{1}".jFormat(
                        logModel.FsL_Page.jTrim().Length == 0 ? "SysLog" : logModel.FsL_Page.jTrim(),
                        logModel.FnL_IsSystemError == 1 ? "Error/" : "")),
                    logName = DateTime.Now.ToString("yyyyMMddHH") + ".log",
                    detail = string.Join(", ", logModel.Detail.Select(kvp => $"{kvp.Key}:{kvp.Value}")),
                    log = sb.ToString()                    
                });
            };
            func.BeginInvoke(new AsyncCallback((ar) => { func.EndInvoke(ar); }), null);
        }

        public static void Log(string path, object value)
        {
            value = value == null ? "object is null" : value;
            Log(path, "{0}", value);
        }

        public static void Log(string path, string format, params object[] arg)
        {
            Action func = new Action(() =>
            {
                if (System.Configuration.ConfigurationManager.AppSettings[path] == "1")
                {
                    var sb = new StringBuilder();
                    sb.AppendFormat("{0} ================", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")).AppendLine();
                    sb.AppendFormat(format, arg).AppendLine();

                    LogCache.Instance.AddQueue(new LogData()
                    {
                        logDir = AppDomain.CurrentDomain.BaseDirectory
                            + @"\privateFolder"
                            + string.Format(@"\{0}\", (string.IsNullOrWhiteSpace(path) ? "SysLog" : path.Trim()).TrimStart('\\').TrimEnd('\\')),
                        logName = DateTime.Now.ToString("yyyyMMddHH") + ".log",
                        log = sb.ToString()
                    });
                }
            });
            func.BeginInvoke(ar => { func.EndInvoke(ar); }, null);
        }

        public static YYS.AliOssConfig GetAliOssConfig()
        {
            var oss = new YYS.AliOssConfig()
            {
                accessKeyId = "LTAI5t7N8g6hhX2kFn5yMmwj",
                accessKeySecret = "GWTJcNGqGUDVqZX3bJL0nNIXfQWmbT",
                bucketName = "ynz1901",
                endpoint = "https://oss-cn-shanghai.aliyuncs.com",
            };
            oss.hostName = oss.endpoint.jTrim().Replace("https://", "https://" + oss.bucketName + ".");
            return oss;
        }

        /// <summary>
        /// 将电话号码替换为*号
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public static string ReplacePhone(string Phone)
        {
            Phone = Phone == null ? "" : Phone.Trim();
            if (Phone.Length > 6)
            {
                if (new System.Text.RegularExpressions.Regex(@"^\d{7,}$").Match(Phone).Success)
                {
                    if (Phone.Length == 11)
                    {
                        Phone = Phone.Substring(0, 3) + "****" + Phone.Substring(7, 4);
                    }
                    else if (Phone.Length == 12)
                    {
                        Phone = Phone.Substring(0, 4) + "****" + Phone.Substring(8, 4);
                    }
                    else if (Phone.Length == 7)
                    {
                        Phone = Phone.Substring(0, 2) + "**" + Phone.Substring(4, 3);
                    }
                    else if (Phone.Length == 8)
                    {
                        Phone = Phone.Substring(0, 2) + "***" + Phone.Substring(5, 3);
                    }
                }
                else if (Phone.Contains("、"))
                {
                    var arr = Phone.Split('、');
                    string okPhone = "";
                    foreach (var s in arr)
                    {
                        okPhone += ReplacePhone(s) + "、";
                    }
                    Phone = okPhone.TrimEnd('、');
                }
                else if (Phone.Contains(","))
                {
                    var arr = Phone.Split(',');
                    string okPhone = "";
                    foreach (var s in arr)
                    {
                        okPhone += ReplacePhone(s) + ",";
                    }
                    Phone = okPhone.TrimEnd(',');
                }
            }
            return Phone;
        }


    }

    /// <summary>
    /// 分布式服务器类型
    /// </summary>
    internal enum mServerType
    {
        /// <summary>
        /// 无
        /// </summary>
        Default = 0,
        /// <summary>
        /// 基础信息分布式服务器
        /// </summary>
        Base = 1,
        /// <summary>
        /// 消费信息分布式服务器
        /// </summary>
        Exp = 2,
        /// <summary>
        /// 基础信息分布式服务器与消费信息分布式服务器
        /// </summary>
        All = 3
    }

    /// <summary>
    /// 常量
    /// </summary>
    public class ConstValue
    {
        //http://129.1.8.188/MWS/mws_PayMoney.asmx
        public const string PMName = "mws_PayMoney";
        public const string PMPwd = "mws_PM_0000";

        public const string strML_Username = "mws_MoneyList";
        public const string strML_Password = "mws_ML_0000";

        public const string strME_Username = "mws_MoneyError";
        public const string strME_Password = "mws_ME_0000";

        public const string strMO_Username = "redone";
        public const string strMO_Password = "SuperStar@2004";

        //
        public const string MTServicePwd = "MTServiceForHXT2012";

        //LogService
        public const string LogServiceName = "LogServiceForHXT2012";
        public const string LogServicePwd = "LogService_111111";

        /// <summary>
        /// All PassWord
        /// </summary>
        public const string ServiceName = "HXTService_2012_Administrator";
        /// <summary>
        /// All Access
        /// </summary>
        public const string ServicePwd = "HXTAccess_2012_Administrator";

        /// <summary>
        /// 验证调用的用户名和密码：验证通过返回“null”，否则返回“非法请求”
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public static string Valid(string name, string pwd)
        {
            if (name == ServiceName && pwd == ServicePwd)
            {
                return null;
            }
            return "非法请求";
        }

    }
}